import {Net, SendLoginWithRes, HttpOption} from "mvx-foundation";
import {DefaultConstructor} from "mvx-utils"

export const waitingRegistry = new Map<String, ((err: Error|null)=>void)[]>();

export function RegisterAutoLogin<T extends object>(net:Net, uri:string, requestF:()=>Promise<object>,
                                                    resType:DefaultConstructor<T>,
                                                    resParser:(res:T) => {uid:string, token:string},
                                                    loginFail:(err: Error)=>Promise<void>,
                                                    ...options:HttpOption[]) {

  waitingRegistry.set(net.getBaseUrl(), []);
  net.set401Delegate(async net =>{
    let [_, err] = await SendLoginWithRes(uri,
      await requestF(), resType, net, resParser, ...options);

    let waiting = waitingRegistry.get(net.getBaseUrl())!;
    for (let w of waiting) {
      w(err)
    }

    waitingRegistry.set(net.getBaseUrl(), []);

    if (err) {
      await loginFail(err)
    }
  })
}

export function UnRegisterAutoLogin(net:Net, net401delegate:(net:Net)=>Promise<void>) {
  net.set401Delegate(net401delegate);
  waitingRegistry.delete(net.getBaseUrl());
}

